package com.fulu.game.bi.mysql.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.fulu.game.bi.mysql.properties.MultipleDatabaseProperties;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

@Slf4j
public class AbstractDbConfig {

    protected DruidDataSource getDruidDataSource(DataSourceProperties dbProperties) {
        DruidDataSource dataSource = new DruidDataSource ();
        dataSource.setDriverClassName (dbProperties.getDriverClassName ());
        dataSource.setUrl (dbProperties.getUrl ());
        dataSource.setUsername (dbProperties.getUsername ());
        dataSource.setPassword (dbProperties.getPassword ());
        dataSource.setInitialSize (10);
        dataSource.setMinIdle (10);
        dataSource.setMaxActive (300);
        dataSource.setMaxWait (30000);
        dataSource.setRemoveAbandoned (true);
        dataSource.setRemoveAbandonedTimeout (1800);
        dataSource.setLogAbandoned (false);
        dataSource.setTimeBetweenEvictionRunsMillis (60000);
        dataSource.setMinEvictableIdleTimeMillis (300000);
        dataSource.setValidationQuery ("SELECT 1");
        dataSource.setTestWhileIdle (true);
        dataSource.setTestOnBorrow (false);
        dataSource.setTestOnReturn (false);
        dataSource.setPoolPreparedStatements (true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize (500);
        dataSource.setKeepAlive (true);
        dataSource.setDbType ("mysql");
        try
        {
            dataSource.setFilters ("druidWebStatFilter,stat-filter,log-filter,stat");
        }
        catch (Exception e)
        {
            log.error ("设置过滤器异常:", e);
        }
        return dataSource;
    }

    /**
     * 获取连接工厂
     */
    protected SqlSessionFactory getSqlSessionFactory(DataSource dataSource, String locationPattern) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean ();
        bean.setDataSource (dataSource);

        // 分页插件
        PageHelper pageHelper = new PageHelper ();
        Properties properties = new Properties ();
        // false: pageNum<1和大于总页数时，返回空;true: pageNum<1返回第一页，大于总页数返回最后一页
        properties.setProperty ("reasonable", "false");
        properties.setProperty ("supportMethodsArguments", "true");
        properties.setProperty ("returnPageInfo", "check");
        properties.setProperty ("params", "count=countSql");
        pageHelper.setProperties (properties);

        // 添加插件
        bean.setPlugins (new Interceptor[]{ pageHelper });
        List <Resource> resources = new ArrayList <Resource> ();
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver ();
        resources.addAll (Arrays.asList (pathMatchingResourcePatternResolver.getResources (locationPattern)));
        bean.setMapperLocations (resources.toArray (new Resource[resources.size ()]));
        bean.getObject ().getConfiguration ().setMapUnderscoreToCamelCase (true);
        return bean.getObject ();
    }
}
